"""
智能消息路由器实现

提供高级的消息路由和协作优化功能，包括：
- 基于机器学习的路由决策
- 动态负载均衡
- 协作模式识别和优化
- 实时性能监控和调整
"""
import json
import asyncio
import numpy as np
from typing import List, Dict, Any, Optional, Tuple, Set
from datetime import datetime, timedelta
from dataclasses import dataclass, field
from collections import defaultdict, deque
from enum import Enum

from .agent_communication_service import (
    AgentCommunicationService, AgentMessage, MessageType, MessagePriority,
    CollaborationSession, CommunicationMetrics
)
from ..models.analysis_models import Context


class RoutingStrategy(Enum):
    """路由策略枚举"""
    DIRECT = "direct"
    LOAD_BALANCED = "load_balanced"
    PRIORITY_BASED = "priority_based"
    CONTEXT_AWARE = "context_aware"
    COLLABORATIVE = "collaborative"


class CollaborationPattern(Enum):
    """协作模式枚举"""
    HIERARCHICAL = "hierarchical"  # 层次化协作
    PEER_TO_PEER = "peer_to_peer"  # 点对点协作
    BROADCAST = "broadcast"        # 广播模式
    WORKFLOW = "workflow"          # 工作流模式
    DYNAMIC = "dynamic"           # 动态协作


@dataclass
class RoutingDecision:
    """路由决策"""
    message_id: str
    original_receiver: str
    recommended_receiver: str
    routing_strategy: RoutingStrategy
    confidence_score: float
    reasoning: str
    alternative_routes: List[str] = field(default_factory=list)
    estimated_delay: float = 0.0
    resource_cost: float = 0.0


@dataclass
class CollaborationOptimization:
    """协作优化建议"""
    session_id: str
    current_pattern: CollaborationPattern
    recommended_pattern: CollaborationPattern
    optimization_actions: List[str] = field(default_factory=list)
    expected_improvement: float = 0.0
    implementation_cost: float = 0.0


class IntelligentMessageRouter:
    """智能消息路由器"""
    
    def __init__(self, communication_service: AgentCommunicationService):
        self.communication_service = communication_service
        
        # 路由学习和优化
        self.routing_history: Dict[str, List[RoutingDecision]] = defaultdict(list)
        self.performance_metrics: Dict[str, Dict[str, float]] = defaultdict(dict)
        self.agent_workload: Dict[str, float] = defaultdict(float)
        self.agent_expertise: Dict[str, Dict[str, float]] = defaultdict(dict)
        
        # 协作模式分析
        self.collaboration_patterns: Dict[str, CollaborationPattern] = {}
        self.pattern_performance: Dict[CollaborationPattern, Dict[str, float]] = defaultdict(dict)
        
        # 实时监控
        self.message_flow_stats: Dict[str, deque] = defaultdict(lambda: deque(maxlen=1000))
        self.bottleneck_detection: Dict[str, List[datetime]] = defaultdict(list)
        
        # 配置参数
        self.config = {
            'learning_rate': 0.1,
            'workload_decay_factor': 0.95,
            'expertise_update_threshold': 0.8,
            'bottleneck_threshold': 10,  # 消息数量阈值
            'optimization_interval': 300,  # 5分钟
            'pattern_analysis_window': 3600,  # 1小时
            'max_routing_alternatives': 3
        }
    
    async def route_message_intelligently(self, message: AgentMessage) -> RoutingDecision:
        """智能路由消息"""
        try:
            # 分析消息上下文
            context = await self._analyze_message_context(message)
            
            # 评估接收者状态
            receiver_status = await self._evaluate_receiver_status(message.receiver_id)
            
            # 选择最佳路由策略
            strategy = await self._select_routing_strategy(message, context, receiver_status)
            
            # 生成路由决策
            decision = await self._generate_routing_decision(message, strategy, context)
            
            # 记录决策用于学习
            self.routing_history[message.message_id].append(decision)
            
            # 更新性能指标
            await self._update_routing_metrics(decision)
            
            return decision
            
        except Exception as e:
            print(f"智能路由失败: {e}")
            # 返回默认直接路由
            return RoutingDecision(
                message_id=message.message_id,
                original_receiver=message.receiver_id,
                recommended_receiver=message.receiver_id,
                routing_strategy=RoutingStrategy.DIRECT,
                confidence_score=0.5,
                reasoning="路由分析失败，使用默认直接路由"
            )
    
    async def optimize_collaboration_pattern(self, session_id: str) -> CollaborationOptimization:
        """优化协作模式"""
        try:
            if session_id not in self.communication_service.collaboration_sessions:
                raise ValueError(f"协作会话不存在: {session_id}")
            
            session = self.communication_service.collaboration_sessions[session_id]
            
            # 分析当前协作模式
            current_pattern = await self._analyze_current_collaboration_pattern(session)
            
            # 评估模式性能
            pattern_performance = await self._evaluate_pattern_performance(session, current_pattern)
            
            # 推荐最佳模式
            recommended_pattern = await self._recommend_optimal_pattern(session, pattern_performance)
            
            # 生成优化建议
            optimization = await self._generate_optimization_suggestions(
                session, current_pattern, recommended_pattern
            )
            
            return optimization
            
        except Exception as e:
            print(f"协作模式优化失败: {e}")
            return CollaborationOptimization(
                session_id=session_id,
                current_pattern=CollaborationPattern.DYNAMIC,
                recommended_pattern=CollaborationPattern.DYNAMIC,
                optimization_actions=["无法分析，保持当前模式"],
                expected_improvement=0.0
            )
    
    async def detect_and_resolve_bottlenecks(self) -> Dict[str, Any]:
        """检测和解决通信瓶颈"""
        try:
            bottlenecks = await self._detect_communication_bottlenecks()
            resolutions = []
            
            for bottleneck in bottlenecks:
                resolution = await self._resolve_bottleneck(bottleneck)
                if resolution:
                    resolutions.append(resolution)
            
            return {
                'bottlenecks_detected': len(bottlenecks),
                'bottlenecks_resolved': len(resolutions),
                'resolutions': resolutions,
                'system_health_improvement': await self._calculate_health_improvement(resolutions)
            }
            
        except Exception as e:
            print(f"瓶颈检测和解决失败: {e}")
            return {'error': '瓶颈处理失败'}
    
    async def _analyze_message_context(self, message: AgentMessage) -> Dict[str, Any]:
        """分析消息上下文"""
        context = {
            'urgency_score': self._calculate_urgency_score(message),
            'complexity_score': self._calculate_complexity_score(message),
            'collaboration_requirement': self._assess_collaboration_requirement(message),
            'expertise_required': self._identify_required_expertise(message),
            'resource_intensity': self._estimate_resource_intensity(message)
        }
        
        return context
    
    def _calculate_urgency_score(self, message: AgentMessage) -> float:
        """计算消息紧急程度"""
        base_score = message.priority.value / 5.0  # 标准化到0-1
        
        # 考虑时间因素
        if message.expires_at:
            time_remaining = (message.expires_at - datetime.now()).total_seconds()
            if time_remaining < 3600:  # 1小时内
                base_score += 0.3
            elif time_remaining < 86400:  # 24小时内
                base_score += 0.1
        
        # 考虑消息类型
        if message.message_type == MessageType.COORDINATION:
            base_score += 0.2
        elif message.message_type == MessageType.STATUS_UPDATE:
            base_score += 0.1
        
        return min(base_score, 1.0)
    
    def _calculate_complexity_score(self, message: AgentMessage) -> float:
        """计算消息复杂度"""
        complexity = 0.0
        
        # 基于内容长度
        content_length = len(str(message.content))
        complexity += min(content_length / 1000, 0.5)  # 最多0.5分
        
        # 基于数据结构复杂度
        if isinstance(message.content, dict):
            nested_levels = self._count_nested_levels(message.content)
            complexity += min(nested_levels / 10, 0.3)  # 最多0.3分
        
        # 基于是否需要响应
        if message.requires_response:
            complexity += 0.2
        
        return min(complexity, 1.0)
    
    def _count_nested_levels(self, obj, level=0):
        """计算嵌套层级数"""
        if not isinstance(obj, (dict, list)):
            return level
        
        max_level = level
        if isinstance(obj, dict):
            for value in obj.values():
                max_level = max(max_level, self._count_nested_levels(value, level + 1))
        elif isinstance(obj, list):
            for item in obj:
                max_level = max(max_level, self._count_nested_levels(item, level + 1))
        
        return max_level
    
    def _assess_collaboration_requirement(self, message: AgentMessage) -> float:
        """评估协作需求"""
        collaboration_score = 0.0
        
        # 基于消息类型
        if message.message_type in [MessageType.COORDINATION, MessageType.KNOWLEDGE_SHARE]:
            collaboration_score += 0.4
        elif message.message_type == MessageType.RESOURCE_SHARE:
            collaboration_score += 0.3
        
        # 基于内容关键词
        content_str = str(message.content).lower()
        collaboration_keywords = ['协作', '合作', '讨论', '会议', '团队', '共同', '一起']
        
        for keyword in collaboration_keywords:
            if keyword in content_str:
                collaboration_score += 0.1
        
        return min(collaboration_score, 1.0)
    
    def _identify_required_expertise(self, message: AgentMessage) -> List[str]:
        """识别所需专业知识"""
        content_str = str(message.content).lower()
        expertise_areas = []
        
        # 技术领域关键词映射
        expertise_keywords = {
            'machine_learning': ['机器学习', '深度学习', '神经网络', '算法', 'ml', 'ai'],
            'data_analysis': ['数据分析', '统计', '可视化', '数据挖掘'],
            'research_methodology': ['研究方法', '实验设计', '文献综述', '假设'],
            'software_engineering': ['编程', '代码', '软件', '开发', '系统'],
            'academic_writing': ['论文', '写作', '发表', '期刊', '会议']
        }
        
        for area, keywords in expertise_keywords.items():
            if any(keyword in content_str for keyword in keywords):
                expertise_areas.append(area)
        
        return expertise_areas
    
    def _estimate_resource_intensity(self, message: AgentMessage) -> float:
        """估算资源强度"""
        intensity = 0.0
        
        # 基于消息复杂度
        intensity += self._calculate_complexity_score(message) * 0.4
        
        # 基于紧急程度
        intensity += self._calculate_urgency_score(message) * 0.3
        
        # 基于协作需求
        intensity += self._assess_collaboration_requirement(message) * 0.3
        
        return min(intensity, 1.0)
    
    async def _evaluate_receiver_status(self, agent_id: str) -> Dict[str, Any]:
        """评估接收者状态"""
        status = {
            'workload': self.agent_workload.get(agent_id, 0.0),
            'availability': await self._calculate_agent_availability(agent_id),
            'expertise_match': 0.0,  # 将在路由决策中计算
            'response_time_avg': await self._get_average_response_time(agent_id),
            'collaboration_score': await self._get_collaboration_score(agent_id)
        }
        
        return status
    
    async def _calculate_agent_availability(self, agent_id: str) -> float:
        """计算Agent可用性"""
        # 基于消息队列长度
        queue_length = len(self.communication_service.message_queue.get(agent_id, []))
        queue_factor = max(0, 1 - queue_length / 50)  # 假设50条消息为满负荷
        
        # 基于活跃协作会话数
        active_sessions = sum(1 for session in self.communication_service.collaboration_sessions.values()
                            if agent_id in session.participants and session.status == "active")
        session_factor = max(0, 1 - active_sessions / 5)  # 假设5个会话为满负荷
        
        # 基于最近响应时间
        recent_response_time = await self._get_recent_response_time(agent_id)
        response_factor = 1.0 if recent_response_time < 300 else 0.5  # 5分钟为阈值
        
        return (queue_factor * 0.4 + session_factor * 0.3 + response_factor * 0.3)
    
    async def _get_average_response_time(self, agent_id: str) -> float:
        """获取平均响应时间"""
        response_times = []
        cutoff_time = datetime.now() - timedelta(days=7)
        
        for message in self.communication_service.message_history.values():
            if (message.receiver_id == agent_id and 
                message.response_message_id and 
                message.timestamp > cutoff_time):
                
                response_msg = self.communication_service.message_history.get(message.response_message_id)
                if response_msg:
                    response_time = (response_msg.timestamp - message.timestamp).total_seconds()
                    response_times.append(response_time)
        
        return sum(response_times) / len(response_times) if response_times else 300.0
    
    async def _get_recent_response_time(self, agent_id: str) -> float:
        """获取最近响应时间"""
        recent_responses = []
        cutoff_time = datetime.now() - timedelta(hours=24)
        
        for message in self.communication_service.message_history.values():
            if (message.receiver_id == agent_id and 
                message.response_message_id and 
                message.timestamp > cutoff_time):
                
                response_msg = self.communication_service.message_history.get(message.response_message_id)
                if response_msg:
                    response_time = (response_msg.timestamp - message.timestamp).total_seconds()
                    recent_responses.append(response_time)
        
        return sum(recent_responses) / len(recent_responses) if recent_responses else 300.0
    
    async def _get_collaboration_score(self, agent_id: str) -> float:
        """获取协作分数"""
        metrics = await self.communication_service.get_communication_metrics(agent_id, days=7)
        return metrics.get('collaboration_score', 0.5)
    
    async def _select_routing_strategy(self, message: AgentMessage, context: Dict[str, Any], 
                                     receiver_status: Dict[str, Any]) -> RoutingStrategy:
        """选择路由策略"""
        # 高紧急度消息使用优先级路由
        if context['urgency_score'] > 0.8:
            return RoutingStrategy.PRIORITY_BASED
        
        # 高协作需求使用协作路由
        if context['collaboration_requirement'] > 0.7:
            return RoutingStrategy.COLLABORATIVE
        
        # 接收者负载过高使用负载均衡
        if receiver_status['workload'] > 0.8 or receiver_status['availability'] < 0.3:
            return RoutingStrategy.LOAD_BALANCED
        
        # 复杂消息使用上下文感知路由
        if context['complexity_score'] > 0.6:
            return RoutingStrategy.CONTEXT_AWARE
        
        # 默认使用直接路由
        return RoutingStrategy.DIRECT
    
    async def _generate_routing_decision(self, message: AgentMessage, strategy: RoutingStrategy, 
                                       context: Dict[str, Any]) -> RoutingDecision:
        """生成路由决策"""
        if strategy == RoutingStrategy.DIRECT:
            return await self._direct_routing(message, context)
        elif strategy == RoutingStrategy.LOAD_BALANCED:
            return await self._load_balanced_routing(message, context)
        elif strategy == RoutingStrategy.PRIORITY_BASED:
            return await self._priority_based_routing(message, context)
        elif strategy == RoutingStrategy.CONTEXT_AWARE:
            return await self._context_aware_routing(message, context)
        elif strategy == RoutingStrategy.COLLABORATIVE:
            return await self._collaborative_routing(message, context)
        else:
            return await self._direct_routing(message, context)
    
    async def _direct_routing(self, message: AgentMessage, context: Dict[str, Any]) -> RoutingDecision:
        """直接路由"""
        return RoutingDecision(
            message_id=message.message_id,
            original_receiver=message.receiver_id,
            recommended_receiver=message.receiver_id,
            routing_strategy=RoutingStrategy.DIRECT,
            confidence_score=0.9,
            reasoning="消息适合直接发送给指定接收者",
            estimated_delay=0.0,
            resource_cost=context['resource_intensity']
        )
    
    async def _load_balanced_routing(self, message: AgentMessage, context: Dict[str, Any]) -> RoutingDecision:
        """负载均衡路由"""
        # 寻找负载较低的替代接收者
        alternative_receivers = await self._find_alternative_receivers(
            message.receiver_id, context['expertise_required']
        )
        
        if alternative_receivers:
            best_alternative = min(alternative_receivers, 
                                 key=lambda x: self.agent_workload.get(x, 0.0))
            
            return RoutingDecision(
                message_id=message.message_id,
                original_receiver=message.receiver_id,
                recommended_receiver=best_alternative,
                routing_strategy=RoutingStrategy.LOAD_BALANCED,
                confidence_score=0.8,
                reasoning=f"原接收者负载过高，推荐转发给负载较低的 {best_alternative}",
                alternative_routes=alternative_receivers[:3],
                estimated_delay=30.0,  # 转发延迟
                resource_cost=context['resource_intensity'] * 0.9
            )
        
        # 如果没有合适的替代者，仍然直接发送
        return await self._direct_routing(message, context)
    
    async def _priority_based_routing(self, message: AgentMessage, context: Dict[str, Any]) -> RoutingDecision:
        """基于优先级的路由"""
        # 对于高优先级消息，可能需要同时通知多个相关人员
        if context['urgency_score'] > 0.9:
            # 找到相关的协调者或上级
            coordinators = await self._find_coordinators(message.receiver_id)
            
            return RoutingDecision(
                message_id=message.message_id,
                original_receiver=message.receiver_id,
                recommended_receiver=message.receiver_id,
                routing_strategy=RoutingStrategy.PRIORITY_BASED,
                confidence_score=0.95,
                reasoning="高优先级消息，建议同时通知相关协调者",
                alternative_routes=coordinators,
                estimated_delay=0.0,
                resource_cost=context['resource_intensity'] * 1.2
            )
        
        return await self._direct_routing(message, context)
    
    async def _context_aware_routing(self, message: AgentMessage, context: Dict[str, Any]) -> RoutingDecision:
        """上下文感知路由"""
        # 基于专业知识匹配寻找最佳接收者
        best_expert = await self._find_best_expert(context['expertise_required'])
        
        if best_expert and best_expert != message.receiver_id:
            expertise_score = await self._calculate_expertise_match(best_expert, context['expertise_required'])
            
            if expertise_score > 0.8:
                return RoutingDecision(
                    message_id=message.message_id,
                    original_receiver=message.receiver_id,
                    recommended_receiver=best_expert,
                    routing_strategy=RoutingStrategy.CONTEXT_AWARE,
                    confidence_score=expertise_score,
                    reasoning=f"基于专业知识匹配，推荐转发给专家 {best_expert}",
                    estimated_delay=60.0,
                    resource_cost=context['resource_intensity'] * 0.8
                )
        
        return await self._direct_routing(message, context)
    
    async def _collaborative_routing(self, message: AgentMessage, context: Dict[str, Any]) -> RoutingDecision:
        """协作路由"""
        # 对于需要协作的消息，创建或加入协作会话
        relevant_session = await self._find_relevant_collaboration_session(message, context)
        
        if relevant_session:
            # 将消息路由到协作会话的所有参与者
            session = self.communication_service.collaboration_sessions[relevant_session]
            
            return RoutingDecision(
                message_id=message.message_id,
                original_receiver=message.receiver_id,
                recommended_receiver=session.coordinator_id,
                routing_strategy=RoutingStrategy.COLLABORATIVE,
                confidence_score=0.85,
                reasoning=f"消息需要协作处理，路由到协作会话 {relevant_session}",
                alternative_routes=session.participants,
                estimated_delay=120.0,
                resource_cost=context['resource_intensity'] * 1.5
            )
        
        return await self._direct_routing(message, context)
    
    async def _find_alternative_receivers(self, original_receiver: str, expertise_required: List[str]) -> List[str]:
        """寻找替代接收者"""
        alternatives = []
        
        # 基于专业知识匹配
        for agent_id, expertise in self.agent_expertise.items():
            if agent_id != original_receiver:
                match_score = 0.0
                for area in expertise_required:
                    match_score += expertise.get(area, 0.0)
                
                if match_score > 0.5:  # 阈值
                    alternatives.append(agent_id)
        
        # 按工作负载排序
        alternatives.sort(key=lambda x: self.agent_workload.get(x, 0.0))
        
        return alternatives[:self.config['max_routing_alternatives']]
    
    async def _find_coordinators(self, agent_id: str) -> List[str]:
        """寻找协调者"""
        coordinators = []
        
        # 查找活跃协作会话中的协调者
        for session in self.communication_service.collaboration_sessions.values():
            if (agent_id in session.participants and 
                session.status == "active" and 
                session.coordinator_id != agent_id):
                coordinators.append(session.coordinator_id)
        
        return list(set(coordinators))  # 去重
    
    async def _find_best_expert(self, expertise_required: List[str]) -> Optional[str]:
        """寻找最佳专家"""
        if not expertise_required:
            return None
        
        best_expert = None
        best_score = 0.0
        
        for agent_id, expertise in self.agent_expertise.items():
            score = 0.0
            for area in expertise_required:
                score += expertise.get(area, 0.0)
            
            # 考虑可用性
            availability = await self._calculate_agent_availability(agent_id)
            adjusted_score = score * availability
            
            if adjusted_score > best_score:
                best_score = adjusted_score
                best_expert = agent_id
        
        return best_expert if best_score > 0.6 else None
    
    async def _calculate_expertise_match(self, agent_id: str, expertise_required: List[str]) -> float:
        """计算专业知识匹配度"""
        if not expertise_required:
            return 0.5
        
        agent_expertise = self.agent_expertise.get(agent_id, {})
        total_score = 0.0
        
        for area in expertise_required:
            total_score += agent_expertise.get(area, 0.0)
        
        return min(total_score / len(expertise_required), 1.0)
    
    async def _find_relevant_collaboration_session(self, message: AgentMessage, 
                                                 context: Dict[str, Any]) -> Optional[str]:
        """寻找相关的协作会话"""
        # 检查发送者和接收者是否已在某个协作会话中
        for session_id, session in self.communication_service.collaboration_sessions.items():
            if (session.status == "active" and 
                message.sender_id in session.participants and 
                message.receiver_id in session.participants):
                return session_id
        
        # 基于消息内容寻找相关会话
        content_keywords = self._extract_keywords(str(message.content))
        
        for session_id, session in self.communication_service.collaboration_sessions.items():
            if session.status == "active":
                session_keywords = self._extract_keywords(" ".join(session.objectives))
                
                # 计算关键词重叠度
                overlap = len(set(content_keywords) & set(session_keywords))
                if overlap > 0:
                    return session_id
        
        return None
    
    def _extract_keywords(self, text: str) -> List[str]:
        """提取关键词"""
        # 简化的关键词提取
        import re
        words = re.findall(r'\b\w+\b', text.lower())
        
        # 过滤停用词
        stop_words = {'的', '是', '在', '有', '和', '与', '或', '但', '如果', '因为', '所以'}
        keywords = [word for word in words if len(word) > 2 and word not in stop_words]
        
        return keywords[:10]  # 返回前10个关键词
    
    async def _update_routing_metrics(self, decision: RoutingDecision):
        """更新路由指标"""
        # 更新工作负载
        self.agent_workload[decision.recommended_receiver] += decision.resource_cost
        
        # 应用衰减因子
        for agent_id in self.agent_workload:
            self.agent_workload[agent_id] *= self.config['workload_decay_factor']
        
        # 记录性能指标
        self.performance_metrics[decision.routing_strategy.value]['decisions_made'] = \
            self.performance_metrics[decision.routing_strategy.value].get('decisions_made', 0) + 1
        
        self.performance_metrics[decision.routing_strategy.value]['avg_confidence'] = \
            (self.performance_metrics[decision.routing_strategy.value].get('avg_confidence', 0.5) + 
             decision.confidence_score) / 2
    
    async def _analyze_current_collaboration_pattern(self, session: CollaborationSession) -> CollaborationPattern:
        """分析当前协作模式"""
        # 分析消息流模式
        message_flows = await self._analyze_session_message_flows(session.session_id)
        
        # 基于消息流特征判断协作模式
        if self._is_hierarchical_pattern(message_flows):
            return CollaborationPattern.HIERARCHICAL
        elif self._is_peer_to_peer_pattern(message_flows):
            return CollaborationPattern.PEER_TO_PEER
        elif self._is_broadcast_pattern(message_flows):
            return CollaborationPattern.BROADCAST
        elif self._is_workflow_pattern(message_flows):
            return CollaborationPattern.WORKFLOW
        else:
            return CollaborationPattern.DYNAMIC
    
    async def _analyze_session_message_flows(self, session_id: str) -> Dict[str, Any]:
        """分析会话消息流"""
        flows = {
            'sender_receiver_pairs': defaultdict(int),
            'message_types': defaultdict(int),
            'time_distribution': [],
            'response_patterns': defaultdict(list)
        }
        
        session_messages = []
        for message in self.communication_service.message_history.values():
            if message.context.get('session_id') == session_id:
                session_messages.append(message)
        
        for message in session_messages:
            pair = (message.sender_id, message.receiver_id)
            flows['sender_receiver_pairs'][pair] += 1
            flows['message_types'][message.message_type.value] += 1
            flows['time_distribution'].append(message.timestamp)
            
            if message.response_message_id:
                response_msg = self.communication_service.message_history.get(message.response_message_id)
                if response_msg:
                    response_time = (response_msg.timestamp - message.timestamp).total_seconds()
                    flows['response_patterns'][message.sender_id].append(response_time)
        
        return flows
    
    def _is_hierarchical_pattern(self, flows: Dict[str, Any]) -> bool:
        """判断是否为层次化模式"""
        # 检查是否有明显的上下级通信模式
        pairs = flows['sender_receiver_pairs']
        
        # 寻找中心节点（接收消息多，发送消息少的节点）
        receivers = defaultdict(int)
        senders = defaultdict(int)
        
        for (sender, receiver), count in pairs.items():
            senders[sender] += count
            receivers[receiver] += count
        
        # 如果存在接收消息远多于发送消息的节点，可能是层次化
        for agent in receivers:
            if receivers[agent] > senders[agent] * 2:
                return True
        
        return False
    
    def _is_peer_to_peer_pattern(self, flows: Dict[str, Any]) -> bool:
        """判断是否为点对点模式"""
        pairs = flows['sender_receiver_pairs']
        
        # 检查双向通信的比例
        bidirectional_pairs = 0
        total_pairs = len(pairs)
        
        for (sender, receiver), count in pairs.items():
            reverse_pair = (receiver, sender)
            if reverse_pair in pairs:
                bidirectional_pairs += 1
        
        # 如果大部分通信都是双向的，可能是点对点模式
        return bidirectional_pairs / total_pairs > 0.6 if total_pairs > 0 else False
    
    def _is_broadcast_pattern(self, flows: Dict[str, Any]) -> bool:
        """判断是否为广播模式"""
        message_types = flows['message_types']
        
        # 如果通知类消息占主导，可能是广播模式
        notification_ratio = message_types.get('notification', 0) / sum(message_types.values())
        return notification_ratio > 0.5
    
    def _is_workflow_pattern(self, flows: Dict[str, Any]) -> bool:
        """判断是否为工作流模式"""
        # 检查消息的时间序列是否显示明显的顺序性
        time_distribution = sorted(flows['time_distribution'])
        
        if len(time_distribution) < 3:
            return False
        
        # 简化的工作流检测：检查是否有明显的阶段性
        time_gaps = []
        for i in range(1, len(time_distribution)):
            gap = (time_distribution[i] - time_distribution[i-1]).total_seconds()
            time_gaps.append(gap)
        
        # 如果存在明显的时间间隔模式，可能是工作流
        avg_gap = sum(time_gaps) / len(time_gaps)
        large_gaps = [gap for gap in time_gaps if gap > avg_gap * 2]
        
        return len(large_gaps) > len(time_gaps) * 0.3
    
    async def _evaluate_pattern_performance(self, session: CollaborationSession, 
                                          pattern: CollaborationPattern) -> Dict[str, float]:
        """评估模式性能"""
        performance = {
            'efficiency': 0.0,
            'response_time': 0.0,
            'participation': 0.0,
            'satisfaction': 0.0
        }
        
        try:
            # 计算效率：完成目标的比例
            completed_objectives = len([obj for obj in session.decisions_made 
                                      if obj.get('status') == 'completed'])
            total_objectives = len(session.objectives)
            performance['efficiency'] = completed_objectives / total_objectives if total_objectives > 0 else 0.0
            
            # 计算平均响应时间
            session_messages = [msg for msg in self.communication_service.message_history.values()
                              if msg.context.get('session_id') == session.session_id]
            
            response_times = []
            for message in session_messages:
                if message.response_message_id:
                    response_msg = self.communication_service.message_history.get(message.response_message_id)
                    if response_msg:
                        response_time = (response_msg.timestamp - message.timestamp).total_seconds()
                        response_times.append(response_time)
            
            performance['response_time'] = 1.0 - min(sum(response_times) / len(response_times) / 3600, 1.0) \
                if response_times else 0.5
            
            # 计算参与度
            participant_activity = defaultdict(int)
            for message in session_messages:
                participant_activity[message.sender_id] += 1
            
            if participant_activity:
                avg_activity = sum(participant_activity.values()) / len(session.participants)
                min_activity = min(participant_activity.values()) if participant_activity else 0
                performance['participation'] = min_activity / avg_activity if avg_activity > 0 else 0.0
            
            # 满意度评估（基于会话持续时间和消息频率）
            if session.start_time:
                session_duration = (datetime.now() - session.start_time).total_seconds()
                message_frequency = len(session_messages) / (session_duration / 3600) if session_duration > 0 else 0
                performance['satisfaction'] = min(message_frequency / 10, 1.0)  # 假设每小时10条消息为理想状态
            
        except Exception as e:
            print(f"评估模式性能失败: {e}")
        
        return performance
    
    async def _recommend_optimal_pattern(self, session: CollaborationSession, 
                                       current_performance: Dict[str, float]) -> CollaborationPattern:
        """推荐最佳协作模式"""
        # 基于会话特征和当前性能推荐最佳模式
        participant_count = len(session.participants)
        objective_count = len(session.objectives)
        
        # 基于参与者数量的推荐
        if participant_count <= 3:
            if current_performance['participation'] < 0.6:
                return CollaborationPattern.PEER_TO_PEER
        elif participant_count <= 6:
            if current_performance['efficiency'] < 0.7:
                return CollaborationPattern.HIERARCHICAL
        else:
            if current_performance['response_time'] < 0.5:
                return CollaborationPattern.BROADCAST
        
        # 基于目标复杂度的推荐
        if objective_count > 5:
            return CollaborationPattern.WORKFLOW
        
        # 如果当前性能良好，保持现有模式
        avg_performance = sum(current_performance.values()) / len(current_performance)
        if avg_performance > 0.7:
            return await self._analyze_current_collaboration_pattern(session)
        
        # 默认推荐动态模式
        return CollaborationPattern.DYNAMIC
    
    async def _generate_optimization_suggestions(self, session: CollaborationSession,
                                               current_pattern: CollaborationPattern,
                                               recommended_pattern: CollaborationPattern) -> CollaborationOptimization:
        """生成优化建议"""
        optimization = CollaborationOptimization(
            session_id=session.session_id,
            current_pattern=current_pattern,
            recommended_pattern=recommended_pattern
        )
        
        if current_pattern == recommended_pattern:
            optimization.optimization_actions = ["当前协作模式已是最优，建议保持"]
            optimization.expected_improvement = 0.0
        else:
            # 根据推荐模式生成具体建议
            if recommended_pattern == CollaborationPattern.HIERARCHICAL:
                optimization.optimization_actions = [
                    "指定明确的协调者角色",
                    "建立清晰的汇报层级",
                    "定期进行状态同步会议",
                    "优化决策流程"
                ]
                optimization.expected_improvement = 0.2
                
            elif recommended_pattern == CollaborationPattern.PEER_TO_PEER:
                optimization.optimization_actions = [
                    "鼓励直接沟通",
                    "减少中间环节",
                    "建立平等的讨论机制",
                    "促进知识共享"
                ]
                optimization.expected_improvement = 0.15
                
            elif recommended_pattern == CollaborationPattern.BROADCAST:
                optimization.optimization_actions = [
                    "建立统一的信息发布渠道",
                    "定期发送进度通报",
                    "减少重复沟通",
                    "优化信息传播效率"
                ]
                optimization.expected_improvement = 0.25
                
            elif recommended_pattern == CollaborationPattern.WORKFLOW:
                optimization.optimization_actions = [
                    "明确任务依赖关系",
                    "建立阶段性检查点",
                    "优化任务分配",
                    "实施进度跟踪机制"
                ]
                optimization.expected_improvement = 0.3
                
            else:  # DYNAMIC
                optimization.optimization_actions = [
                    "根据任务特点灵活调整协作方式",
                    "建立多种沟通渠道",
                    "实时监控协作效果",
                    "快速响应变化需求"
                ]
                optimization.expected_improvement = 0.1
        
        optimization.implementation_cost = len(optimization.optimization_actions) * 0.1
        
        return optimization
    
    async def _detect_communication_bottlenecks(self) -> List[Dict[str, Any]]:
        """检测通信瓶颈"""
        bottlenecks = []
        current_time = datetime.now()
        
        # 检测消息队列瓶颈
        for agent_id, queue in self.communication_service.message_queue.items():
            if len(queue) > self.config['bottleneck_threshold']:
                bottlenecks.append({
                    'type': 'queue_overflow',
                    'agent_id': agent_id,
                    'severity': 'high' if len(queue) > self.config['bottleneck_threshold'] * 2 else 'medium',
                    'details': {
                        'queue_length': len(queue),
                        'threshold': self.config['bottleneck_threshold']
                    }
                })
        
        # 检测响应时间瓶颈
        for agent_id in self.communication_service.message_queue.keys():
            avg_response_time = await self._get_average_response_time(agent_id)
            if avg_response_time > 600:  # 10分钟
                bottlenecks.append({
                    'type': 'slow_response',
                    'agent_id': agent_id,
                    'severity': 'high' if avg_response_time > 1800 else 'medium',  # 30分钟
                    'details': {
                        'avg_response_time': avg_response_time,
                        'threshold': 600
                    }
                })
        
        # 检测协作会话瓶颈
        for session_id, session in self.communication_service.collaboration_sessions.items():
            if session.status == "active":
                session_duration = (current_time - session.start_time).total_seconds()
                if session_duration > self.config['collaboration_timeout_hours'] * 3600:
                    bottlenecks.append({
                        'type': 'stalled_collaboration',
                        'session_id': session_id,
                        'severity': 'medium',
                        'details': {
                            'duration_hours': session_duration / 3600,
                            'threshold_hours': self.config['collaboration_timeout_hours']
                        }
                    })
        
        return bottlenecks
    
    async def _resolve_bottleneck(self, bottleneck: Dict[str, Any]) -> Optional[Dict[str, Any]]:
        """解决瓶颈"""
        resolution = None
        
        try:
            if bottleneck['type'] == 'queue_overflow':
                # 清理过期消息和低优先级消息
                agent_id = bottleneck['agent_id']
                await self.communication_service._cleanup_message_queue(agent_id)
                
                # 寻找替代处理者
                alternatives = await self._find_alternative_receivers(agent_id, [])
                
                resolution = {
                    'bottleneck_type': bottleneck['type'],
                    'action': 'queue_cleanup_and_load_balancing',
                    'details': {
                        'messages_cleaned': bottleneck['details']['queue_length'] - 
                                          len(self.communication_service.message_queue[agent_id]),
                        'alternative_agents': alternatives
                    }
                }
                
            elif bottleneck['type'] == 'slow_response':
                # 降低该Agent的工作负载权重
                agent_id = bottleneck['agent_id']
                self.agent_workload[agent_id] *= 1.5  # 增加负载权重，减少新消息分配
                
                resolution = {
                    'bottleneck_type': bottleneck['type'],
                    'action': 'workload_adjustment',
                    'details': {
                        'agent_id': agent_id,
                        'new_workload_weight': self.agent_workload[agent_id]
                    }
                }
                
            elif bottleneck['type'] == 'stalled_collaboration':
                # 重新激活协作会话
                session_id = bottleneck['session_id']
                session = self.communication_service.collaboration_sessions[session_id]
                
                # 发送重新激活通知
                for participant in session.participants:
                    reactivation_message = AgentMessage(
                        sender_id="system",
                        receiver_id=participant,
                        message_type=MessageType.NOTIFICATION,
                        priority=MessagePriority.HIGH,
                        subject=f"协作会话重新激活: {session.name}",
                        content={
                            'session_id': session_id,
                            'action': 'reactivation',
                            'reason': '会话停滞时间过长'
                        }
                    )
                    await self.communication_service.send_message(reactivation_message)
                
                resolution = {
                    'bottleneck_type': bottleneck['type'],
                    'action': 'session_reactivation',
                    'details': {
                        'session_id': session_id,
                        'participants_notified': len(session.participants)
                    }
                }
                
        except Exception as e:
            print(f"解决瓶颈失败: {e}")
        
        return resolution
    
    async def _calculate_health_improvement(self, resolutions: List[Dict[str, Any]]) -> float:
        """计算系统健康度改善"""
        if not resolutions:
            return 0.0
        
        improvement = 0.0
        
        for resolution in resolutions:
            if resolution['bottleneck_type'] == 'queue_overflow':
                improvement += 0.3
            elif resolution['bottleneck_type'] == 'slow_response':
                improvement += 0.2
            elif resolution['bottleneck_type'] == 'stalled_collaboration':
                improvement += 0.1
        
        return min(improvement, 1.0)
    
    async def get_routing_analytics(self) -> Dict[str, Any]:
        """获取路由分析报告"""
        try:
            analytics = {
                'routing_strategies': {},
                'agent_workloads': dict(self.agent_workload),
                'expertise_distribution': dict(self.agent_expertise),
                'performance_trends': {},
                'optimization_opportunities': []
            }
            
            # 路由策略统计
            for strategy, metrics in self.performance_metrics.items():
                analytics['routing_strategies'][strategy] = {
                    'usage_count': metrics.get('decisions_made', 0),
                    'average_confidence': metrics.get('avg_confidence', 0.0),
                    'success_rate': metrics.get('success_rate', 0.0)
                }
            
            # 性能趋势分析
            for agent_id in self.agent_workload.keys():
                recent_performance = await self._analyze_agent_performance_trend(agent_id)
                analytics['performance_trends'][agent_id] = recent_performance
            
            # 优化机会识别
            optimization_opportunities = await self._identify_optimization_opportunities()
            analytics['optimization_opportunities'] = optimization_opportunities
            
            return analytics
            
        except Exception as e:
            print(f"获取路由分析失败: {e}")
            return {'error': '路由分析失败'}
    
    async def _analyze_agent_performance_trend(self, agent_id: str) -> Dict[str, Any]:
        """分析Agent性能趋势"""
        trend = {
            'workload_trend': 'stable',
            'response_time_trend': 'stable',
            'collaboration_trend': 'stable',
            'recommendations': []
        }
        
        try:
            # 分析工作负载趋势
            current_workload = self.agent_workload.get(agent_id, 0.0)
            if current_workload > 0.8:
                trend['workload_trend'] = 'increasing'
                trend['recommendations'].append('考虑负载均衡')
            elif current_workload < 0.2:
                trend['workload_trend'] = 'decreasing'
                trend['recommendations'].append('可以承担更多任务')
            
            # 分析响应时间趋势
            avg_response_time = await self._get_average_response_time(agent_id)
            if avg_response_time > 600:
                trend['response_time_trend'] = 'deteriorating'
                trend['recommendations'].append('优化响应速度')
            elif avg_response_time < 120:
                trend['response_time_trend'] = 'improving'
            
            # 分析协作趋势
            collaboration_score = await self._get_collaboration_score(agent_id)
            if collaboration_score > 0.8:
                trend['collaboration_trend'] = 'improving'
            elif collaboration_score < 0.4:
                trend['collaboration_trend'] = 'deteriorating'
                trend['recommendations'].append('增加协作参与度')
            
        except Exception as e:
            print(f"分析Agent性能趋势失败: {e}")
        
        return trend
    
    async def _identify_optimization_opportunities(self) -> List[Dict[str, Any]]:
        """识别优化机会"""
        opportunities = []
        
        try:
            # 识别负载不均衡
            workloads = list(self.agent_workload.values())
            if workloads:
                max_workload = max(workloads)
                min_workload = min(workloads)
                
                if max_workload - min_workload > 0.5:
                    opportunities.append({
                        'type': 'load_balancing',
                        'description': '检测到负载不均衡，建议重新分配任务',
                        'priority': 'high',
                        'potential_improvement': 0.3
                    })
            
            # 识别专业知识匹配不当
            mismatched_assignments = 0
            for decision_history in self.routing_history.values():
                for decision in decision_history:
                    if decision.confidence_score < 0.6:
                        mismatched_assignments += 1
            
            if mismatched_assignments > 10:
                opportunities.append({
                    'type': 'expertise_matching',
                    'description': '发现多个专业知识匹配度低的分配，建议优化专家匹配',
                    'priority': 'medium',
                    'potential_improvement': 0.2
                })
            
            # 识别协作模式优化机会
            for session_id, session in self.communication_service.collaboration_sessions.items():
                if session.status == "active":
                    current_pattern = await self._analyze_current_collaboration_pattern(session)
                    performance = await self._evaluate_pattern_performance(session, current_pattern)
                    
                    avg_performance = sum(performance.values()) / len(performance)
                    if avg_performance < 0.6:
                        opportunities.append({
                            'type': 'collaboration_optimization',
                            'description': f'协作会话 {session.name} 性能较低，建议优化协作模式',
                            'priority': 'medium',
                            'potential_improvement': 0.25,
                            'session_id': session_id
                        })
            
        except Exception as e:
            print(f"识别优化机会失败: {e}")
        
        return opportunities